package com.shoppingmall.controller;

import com.shoppingmall.commons.Result;
import com.shoppingmall.model.Car;
import com.shoppingmall.model.view.CarView;
import com.shoppingmall.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {
    @Autowired
    private CarService carService;
    @RequestMapping("/addCar")
    public Result addCar(@RequestBody Car car){
        try {
            Object obj=carService.getCarCount(car);
            if (obj!=null&&(int)obj>0&&(int)obj<100){
                int count = (int)carService.getCarCount(car)+(int)car.getCar_count();
                if(count>=99){
                    int sun=99-(int)carService.getCarCount(car);
                    return Result.fail(500,"超过最大数值,您最多在加入购物车"+sun+"件");
                }
                car.setCar_count(count);
                carService.updateCarCount(car);
                return Result.success("购物车添加成功");
            }else if(obj==null){
                carService.addCar(car);
                return Result.success("购物车添加成功");
            }
            return Result.fail(500,"超过最大数值！");
        } catch (Exception exception) {
            exception.printStackTrace();
            return Result.fail(500,"商品添加失败");
        }
    }
    @GetMapping("/getCarInfo")
    public List<CarView> getCarInfo( int user_id){
        return carService.getCarInfo(user_id);
    }
    @PostMapping("/updateCarCount")
    public void updateCarCount(@RequestBody Car car){
        carService.updateCarCount(car);
    }
    @PostMapping("/delCar")
    public Result delCar(@RequestBody Car car){
        carService.delCar(car);
        return Result.success("删除成功！");
    }
    @PostMapping("/getCarCount")
    public int getCarCount(int user_id){
        return   carService.getUserCarCount(user_id);
    }
}


